﻿using UnityEngine;
using System.Collections;

public class Player : Unit {

	public int life=3;//生命数
    
	public float invicibleTime=3f;//无敌时间
	private float invicibleTimer=0;//无敌计时器
	private Vector3 initPos;//初始位置
	private bool IsInvicible//是否无敌
	{
		get{return invicibleTimer<invicibleTime;}
	}

	protected override void Start ()
    {
        base.Start();
		Idle ();
		initPos = transform.position;
	}

    //移动控制
	private void ContolMove()
	{
		Vector2 pos = transform.position;
		/*if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) {
			Vector2 delta=Input.GetTouch(0).deltaPosition;
			pos.x=Mathf.Clamp (pos.x + delta.x*speed * Time.deltaTime, -8f, 8f);
			pos.y=Mathf.Clamp (pos.y + delta.y* speed * Time.deltaTime, -4.5f, 3.2f);
		}*/
        if(Input.GetKey(KeyCode.W))
            pos.y = Mathf.Clamp(pos.y + speed * Time.deltaTime, -4.5f, 3.2f);
        if (Input.GetKey(KeyCode.S))
            pos.y = Mathf.Clamp(pos.y - speed * Time.deltaTime, -4.5f, 3.2f);
        if (Input.GetKey(KeyCode.A))
            pos.x = Mathf.Clamp(pos.x - speed * Time.deltaTime, -8f, 8f);
        if (Input.GetKey(KeyCode.D))
            pos.x = Mathf.Clamp(pos.x + speed * Time.deltaTime, -8f, 8f);
        transform.position = pos;
	}
	// Update is called once per frame
	void Update () {
		if (isDeath)
			return;
		if (!isflying)
			return;
		ContolMove ();
		fireTimer += Time.deltaTime;
		invicibleTimer += Time.deltaTime;
		Fire();
	}

    //重生
	public void Rebirth()
	{
		invicibleTimer = 0;
		transform.position = initPos;
		hp = maxHp;
	}
    //死亡
	public override void Death()
	{
		if (hp <= 0)
		{
			life--;
            if (life <= 0)
            {
                ani.SetTrigger("Death");
                Destroy(gameObject, 0.3f);
                isDeath = true;
                event_manager.Instance.dispatch_event("OnFail", null);
            }
            else
                 Rebirth();
		}
	}
	

	void OnTriggerEnter2D(Collider2D other)
	{
		if (IsInvicible)
			return;
        //自己的子弹
		if (other.gameObject.tag == "Bullet")
			return;
        //敌人的子弹
		if (other.gameObject.tag=="Bullet1") 
		{
			Bullet b=other.GetComponent<Bullet>();
			hp-=b.power;
			Destroy(other.gameObject);
		}
        //敌人
		if (other.gameObject.tag=="Enemy") 
		{
			Enemy e=other.GetComponent<Enemy>();
			hp-=e.power;
		}
        //导弹
		if (other.gameObject.tag=="Missile") 
		{
			Missile m=other.GetComponent<Missile>();
			hp-=m.power;
			Destroy(other.gameObject);
		}
        //boss
		if (other.gameObject.tag == "Boss") 
		{
			hp=0;
		}
		Death();
	}
	
}
